package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.TimeDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.service.*;
import com.sky.utils.CommonUtil;
import com.sky.utils.ThreadLocalUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.webscket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private IAddressBookService iAddressBookService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IShoppingCartService iShoppingCartService;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submit(Orders order) {
        Long value =(Long) ThreadLocalUtil.getValue();
    //提交订单

        //number订单号
        order.setNumber(CommonUtil.generateOrderNum());
        //状态
//        order.setStatus(Orders.PENDING_PAYMENT);
        //电话
        //根据地址id找电话
        AddressBook addressBook = iAddressBookService.getById(order.getAddressBookId());
        order.setPhone(addressBook.getPhone());
        //地址
        order.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //收货人
        order.setConsignee(addressBook.getConsignee());
        //用户名
        User user = iUserService.getById(value);
        //userId
        order.setUserId(value);
        //userName
        order.setUserName(user.getName());
        //orderTime
        order.setOrderTime(LocalDateTime.now());
        //支付状态
        order.setPayStatus(Orders.UN_PAID);
        this.save(order);
    //提交订单细节表
        //应该根据购物车的几条信息，添加到细节表中
        LambdaQueryWrapper<ShoppingCart> lqw =new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,value);
        List<ShoppingCart> list = iShoppingCartService.list(lqw);
        List<OrderDetail> orderDetailList =new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        iOrderDetailService.saveBatch(orderDetailList);
    //删除购物车
        iShoppingCartService.remove(lqw);
    //返回OrderSubmitVo
        OrderSubmitVO orderSubmitVo = OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .build();
        return orderSubmitVo;
    }

    @Override
    public void paySuccess(String orderNumber) {
        // 根据订单号查询订单
        Orders ordersDB = this.getOne(new LambdaQueryWrapper<Orders>().eq(Orders::getNumber, orderNumber));

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        this.updateById(orders);

        //约定
        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒 2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + orderNumber);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO)  {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        //生成空JSON，跳过微信支付流程
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
/*      // 模拟支付成功，更新数据库订单状态
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);*/

        return vo;
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders ordersDB = this.getById(id);
        if (ordersDB==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map =new HashMap();
        map.put("type", 2);//1表示来单提醒 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号:" + ordersDB.getNumber());

        //向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    @Transactional
    public void repetition(Long orderId) {
        Orders order = this.getById(orderId);
        order.setId(null);
        this.save(order);
        //
        LambdaQueryWrapper<OrderDetail> lqw =new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> list = iOrderDetailService.list(lqw);
        //
        list.forEach(s->{s.setOrderId(order.getId());s.setId(null);});
        iOrderDetailService.saveBatch(list);
    }


}
